﻿using LibNiconico.NiconicoApi.Exceptions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;



namespace LibNiconico.NiconicoApi.Extentions
{
    /// <summary>
    /// URLの問い合わせ部分文字列
    /// </summary>
    public class QueryStrings :Dictionary<string, string>
    {
        /// <summary>
        /// URL問い合わせ部分に整形された文字列として文字列を取得
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder rsltBuilder = new StringBuilder();
            var keys = this.Keys.ToArray();
            for (int index = 0; index < keys.Length; index++)
            {
                rsltBuilder.Append(Uri.EscapeDataString(keys[index]));
                rsltBuilder.Append("=");
                rsltBuilder.Append(Uri.EscapeDataString(this[keys[index]]));
                if (index < keys.Length - 1)
                {
                    rsltBuilder.Append("&");
                }
            }

            return rsltBuilder.ToString();
        }



        /// <summary>
        /// 渡された文字列を解析してQueryStringsオブジェクトに変換
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static QueryStrings Parse(string value)
        {
            try
            {
                string[] queryStringList = value.Split('&');
                QueryStrings queryStrings = new QueryStrings();
                foreach (var queryString in queryStringList)
                {
                    string[] keyValue = queryString.Split('=');
                    if (keyValue.Length == 1) continue;
                    queryStrings.Add(Uri.UnescapeDataString(keyValue[0]),Uri.UnescapeDataString( keyValue[1]));


                }

                return queryStrings;
            }
            catch (Exception e)
            {
                throw new NicoApiException("クエリ文字列生成に失敗しました",e);
            }
        }
    }
}
